package com.springboot2.validate.config;

import com.springboot2.validate.exception.ExceptionResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

/**
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 数据校验异常，@RequestBody
     * @return 异常提示信息实体
     */
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public ExceptionResponseVO methodArgException(MethodArgumentNotValidException mex,
//                                                  HttpServletResponse response, HttpServletRequest request) {
//        FieldError fieldError = mex.getBindingResult().getFieldError();
//        log.info("字段({})校验失败，{}", fieldError.getField(), fieldError.getDefaultMessage());
//        return new ExceptionResponseVO("400", fieldError.getDefaultMessage());
//    }

    /**
     * ConstraintViolationException 是继承RuntimeException
     * @param ex ConstraintViolationException
     * @return ExceptionResponseVO
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ExceptionResponseVO constraintViolationException(ConstraintViolationException ex) {

        log.info("参数校验失败, info = {}", ex.getMessage());
        return new ExceptionResponseVO("400", ex.getMessage());
    }

    /**
     * 处理RuntimeException异常
     * @param response response
     * @param request request
     * @param e e
     * @return ExceptionResponseVO
     */
    @ExceptionHandler(RuntimeException.class)
    public ExceptionResponseVO runtimeExceptionHandler(HttpServletResponse response,
                                                       HttpServletRequest request, Exception e) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        RuntimeException exception = (RuntimeException) e;

        return new ExceptionResponseVO("400", exception.getMessage());
    }

    /**
     * 该方法在父类中已经指定了@ExceptionHandler的参数包含  MethodArgumentNotValidException、BindException
     * 重新定义  @ExceptionHandler(MethodArgumentNotValidException.class) 会报错。
     * 错误信息：Factory method 'handlerExceptionResolver' threw exception; nested exception is
     *      java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for
     * @param ex Exception
     * @param body Object
     * @param headers HttpHeaders
     * @param status HttpStatus
     * @param request WebRequest
     * @return ResponseEntity
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {

        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
            return new ResponseEntity<>(new ExceptionResponseVO(status.value()+"", exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
        }
        if (ex instanceof HttpMessageNotReadableException) {
            log.error("全局异常处理123", ex);
            HttpMessageNotReadableException exception = (HttpMessageNotReadableException) ex;
            return new ResponseEntity<>(new ExceptionResponseVO(status.value()+"", "参数格式错误"), status);
        }

        log.error("全局异常处理", ex);
        return new ResponseEntity<>(new ExceptionResponseVO(status.value() + "", ex.getMessage()), status);
    }
}
